import ReactDOM from 'react-dom/client';

function ConfirmBox({ msg, onOk }) {
  return (
    <div className="confirm-box">
      <div className="content">
        <div className="text">{msg}</div>
        <div className="ok-btn" onClick={onOk}>
          确定
        </div>
      </div>
    </div>
  );
}

export async function showConfirm(msg) {
  return new Promise((resolve) => {
    const div = document.createElement('div');
    document.body.appendChild(div);
    const root = ReactDOM.createRoot(div);
    const onOk = () => {
      document.body.removeChild(div);
      resolve(true);
    };
    root.render(<ConfirmBox msg={msg} onOk={onOk} />);
  });
}

function ToastBox({ msg }) {
  return (
    <div className="toast-box">
      <div className="toast">{msg}</div>
    </div>
  );
}

export function showToast(msg) {
  const div = document.createElement('div');
  document.body.appendChild(div);
  const root = ReactDOM.createRoot(div);
  root.render(<ToastBox msg={msg} />);
  setTimeout(() => {
    root.unmount();
    document.body.removeChild(div);
  }, 3000);
}

export function parseLocationParams(params) {
  if (!params) return undefined;
  let real = params.startsWith('?') ? params.split('?')[1] : params;
  let _tmpList = real.split('&') || [];
  let _data = {};
  for (let _tmp of _tmpList) {
    let [_k, _v] = _tmp.split('=');
    _data[_k] = _v;
  }
  return _data;
}
